import { eventBus } from './../core/common/index'
import https from 'https'
import http from 'http'
import path from 'path'
import { createWriteStream, existsSync, mkdirSync } from 'fs'
import { isHttpsPath } from './utils'
import { EventType } from '../constants/event'

export function download(url: string, destination: string, name?: string) {
  if (!existsSync(destination)) {
    mkdirSync(destination, { recursive: true })
  }
  if (!name) {
    name = path.basename(url.split('?')[0])
  }
  const filePath = path.join(destination, name)
  if (existsSync(filePath)) {
    eventBus.emit(EventType.DownloadComplete, {
      file: url,
      target: filePath,
    })
    return Promise.resolve(filePath)
  }
  const writeStream = createWriteStream(filePath)
  const request = isHttpsPath(url) ? https : http
  request.get(url, (res) => {
    res.pipe(writeStream)
    const totalLength = parseInt(
      res.headers['content-length'] as unknown as string
    )
    let downloadLength = 0
    res.on('data', (chunk) => {
      downloadLength += chunk.length
      eventBus.emit(EventType.DownloadProgress, {
        file: url,
        total: totalLength,
        progress: downloadLength,
      })
    })
  })
  return new Promise((resolve, reject) => {
    writeStream.on('finish', () => {
      eventBus.emit(EventType.DownloadComplete, {
        file: url,
        target: filePath,
      })
      resolve(filePath)
    })
    writeStream.on('error', (err) => {
      eventBus.emit(EventType.DownloadFailed, {
        file: url,
        target: filePath,
        err: err,
      })
      reject(err)
    })
  })
}
